<script lang="ts" setup>
import { CascaderValue, ElMessage, FormRules, FormInstance } from 'element-plus'
import { reactive, ref, watchEffect } from 'vue'
import CustomActiveButton from '@/components/basic/ui-elements/CustomActiveButton.vue'
import CustomActiveButtonGroup from '@/components/basic/ui-elements/CustomActiveButtonGroup.vue'
import { getToken } from '@/utils/cache/cookies'
import { queryDeviceStaff, submitWorkOrder } from '@/api/operation'
import { queryDeviceStaffResponseData } from '@/api/operation/types/operation'
import { workOrderCategoryType, workOrderDeviceType, workOrderUrgencyType } from '@/types/enum'
const dialogVisible = ref<boolean>(false)
const form = reactive({
  deviceCode: '',
  deviceType: '',
  type: '',
  category: '',
  urgency: '',
  imageUrl: '',
  scheduleDuration: '',
  remark: '',
  staffId: '',
  faultId: ''
})
const formRef = ref<FormInstance | null>(null)
const options = [
  {
    value: '故障',
    label: '故障',
    children: [
      {
        value: '故障-用户上报',
        label: '用户上报'
      },
      {
        value: '故障-运维上报',
        label: '运维上报'
      },
      {
        value: '故障-其他',
        label: '其他'
      }
    ]
  },
  {
    value: '换电',
    label: '换电',
    children: [
      {
        value: '换电-短租车换电',
        label: '短租车换电'
      },
      {
        value: '换电-长租车换电',
        label: '长租车换电'
      },
      {
        value: '换电-换电柜换电',
        label: '换电柜换电'
      },
      {
        value: '换电-电池充电',
        label: '电池充电'
      },
      {
        value: '换电-仓库换电',
        label: '仓库换电'
      },
      {
        value: '换电-城管换电',
        label: '城管换电'
      },
      {
        value: '换电-其他',
        label: '其他'
      }
    ]
  },
  {
    value: '调度',
    label: '调度',
    children: [
      {
        value: '调度-投放市场',
        label: '投放市场'
      },
      {
        value: '调度-收回仓库',
        label: '收回仓库'
      },
      {
        value: '调度-调到租赁点',
        label: '调到租赁点'
      },
      {
        value: '调度-区域外调度',
        label: '区域外调度'
      },
      {
        value: '调度-其他',
        label: '其他'
      }
    ]
  },
  {
    value: '巡检',
    label: '巡检',
    children: [
      {
        value: '巡检-停放巡检',
        label: '停放巡检'
      },
      {
        value: '巡检-气候突检',
        label: '气候突检'
      },
      {
        value: '巡检-市容巡检',
        label: '市容巡检'
      },
      {
        value: '巡检-刹车检查',
        label: '刹车检查'
      },
      {
        value: '巡检-坐垫检查',
        label: '坐垫检查'
      },
      {
        value: '巡检-骑行检查',
        label: '骑行检查'
      },
      {
        value: '巡检-头盔检查',
        label: '头盔检查'
      },
      {
        value: '巡检-其他',
        label: '其他'
      }
    ]
  },
  {
    value: '维修',
    label: '维修',
    children: [
      {
        value: '维修-短租车维修',
        label: '短租车维修'
      },
      {
        value: '维修-换电柜维修',
        label: '换电柜维修'
      },
      {
        value: '维修-长租车维修',
        label: '长租车维修'
      },
      {
        value: '维修-电池维修',
        label: '电池维修'
      },
      {
        value: '维修-民用车维修',
        label: '民用车维修'
      },
      {
        value: '维修-其他',
        label: '其他'
      }
    ]
  },
  {
    value: '寻找',
    label: '寻找',
    children: [
      {
        value: '寻找-小区寻车',
        label: '小区寻车'
      },
      {
        value: '寻找-地下室寻车',
        label: '地下室寻车'
      },
      {
        value: '寻找-园区寻车',
        label: '园区寻车'
      },
      {
        value: '寻找-其他',
        label: '其他'
      }
    ]
  },
  {
    value: '事故',
    label: '事故',
    children: [
      {
        value: '事故-车架核对',
        label: '车架核对'
      },
      {
        value: '事故-事故核查',
        label: '事故核查'
      },
      {
        value: '事故-其他',
        label: '其他'
      }
    ]
  }
]
const type = ref<CascaderValue>('')
/** 自定义时长 */
const customizeTime = ref<number>(0)
/** 控制自定义时长的显示 */
const showTime = ref<boolean>(false)
const action = ref<string>(import.meta.env.VITE_API + 'uploadWorkOrderImages')
const emit = defineEmits(['refresh'])
const deviceStaff = ref<null | queryDeviceStaffResponseData>(null)
const receiver = ref<string>('')
const rule = reactive<FormRules>({
  deviceCode: [
    {
      required: true,
      message: '请输入设备编号',
      trigger: 'blur'
    }
  ],
  type: [
    {
      required: true,
      message: '请选择工单分类',
      trigger: 'blur'
    }
  ],
  category: [
    {
      required: true,
      message: '请选择工单二级分类',
      trigger: 'blur'
    }
  ],
  urgency: [
    {
      required: true,
      message: '请选择工单紧急程度',
      trigger: 'blur'
    }
  ],
  scheduleDuration: [
    {
      required: true,
      message: '请选择或输入工单时长',
      trigger: 'blur'
    }
  ],
  remark: [
    {
      required: true,
      message: '请输入工单详情',
      trigger: 'blur'
    }
  ],
  deviceType: [
    {
      required: true,
      message: '请选择设备类型',
      trigger: 'blur'
    }
  ]
})
const queryStaff = async () => {
  try {
    const res = await queryDeviceStaff({
      token: getToken() ?? '',
      deviceCode: form.deviceCode
    })
    if (res.statusCode === '0') {
      deviceStaff.value = res.data
    }
  } catch (error) {
    console.error(error)
  }
}
watchEffect(() => {
  if (form.scheduleDuration === '自定义') {
    showTime.value = true
  } else {
    showTime.value = false
  }
})
const handleCascaderTypeChange = () => {
  form.type = (type.value as string).split('-')[0]
  form.category = (type.value as string).split('-')[1]
}
const handleCascaderReceiverChange = () => {
  form.staffId = receiver.value
}
const OnSuccess = (response: any) => {
  form.imageUrl = form.imageUrl ? form.imageUrl + ',' + response.data : response.data
}
const submit = () => {
  if (form.scheduleDuration === '自定义') {
    form.scheduleDuration = (customizeTime.value * 60).toString()
  }
  formRef.value?.validate(async (valid) => {
    if (valid) {
      const res = await submitWorkOrder({
        token: getToken() ?? '',
        scheduleDuration: form.scheduleDuration,
        staffId: form.staffId,
        remark: form.remark,
        deviceCode: form.deviceCode,
        deviceType: form.deviceType as workOrderDeviceType,
        type: form.type as workOrderCategoryType,
        category: form.category,
        urgency: form.urgency as workOrderUrgencyType,
        imageUrl: form.imageUrl,
        faultId: form.faultId
      })
      if (res.statusCode === '0') {
        ElMessage.success(res.data)
        reset()
        emit('refresh')
      }
    }
  })
}
const reset = () => {
  formRef.value?.resetFields()
  dialogVisible.value = false
}
const open = () => {
  dialogVisible.value = true
}
const setData = (id: string) => {
  form.faultId = id
}

const handleExceed = () => {
  ElMessage.warning('最多只能上传两张图片')
}
const handleCoderBlur = () => {
  if (!form.deviceCode) {
    return
  }
  queryStaff()
}
defineExpose({
  open,
  setData
})
</script>

<template>
  <el-dialog v-model="dialogVisible" title="添加工单" width="500px">
    <el-form :model="form" ref="formRef" :rules="rule" label-position="right" label-width="100px">
      <el-form-item prop="deviceType" label="设备类型">
        <el-select v-model="form.deviceType" placeholder="请选择设备类型">
          <el-option label="短租车" value="短租车" />
          <el-option label="换电柜" value="换电柜" />
          <el-option label="长租车" value="长租车" />
          <el-option label="电池" value="电池" />
          <el-option label="民用车" value="民用车" />
          <el-option label="改装车" value="改装车" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备编号" prop="deviceCode">
        <el-input v-model="form.deviceCode" placeholder="请输入设备编号" @blur="handleCoderBlur" />
      </el-form-item>
      <el-form-item label="工单分类" required prop="type">
        <el-cascader
          v-model="type"
          :options="options"
          separator="-"
          @change="handleCascaderTypeChange"
          :props="{ emitPath: false }"
        />
      </el-form-item>
      <el-form-item
        v-if="form.deviceCode"
        label="接单人"
        required
        prop="staffId"
        :rules="[
          {
            required: true,
            message: '请选择接单人',
            trigger: 'blur'
          }
        ]"
      >
        <el-cascader
          v-model="receiver"
          :options="deviceStaff!!"
          separator="-"
          @change="handleCascaderReceiverChange"
          :props="{ emitPath: false, label: 'name', value: 'id', children: 'staffData' }"
        />
      </el-form-item>
      <el-form-item label="紧急程度" prop="urgency">
        <custom-active-button-group v-model="form.urgency">
          <custom-active-button active-value="紧急" inactive-value="">紧急</custom-active-button>
          <custom-active-button active-value="重要" inactive-value="">重要</custom-active-button>
          <custom-active-button active-value="普通" inactive-value="">普通</custom-active-button>
          <custom-active-button active-value="较低" inactive-value="">较低</custom-active-button>
        </custom-active-button-group>
      </el-form-item>
      <el-form-item label="完成时长" prop="scheduleDuration">
        <custom-active-button-group v-model="form.scheduleDuration">
          <custom-active-button active-value="1800" inactive-value="">30分钟</custom-active-button>
          <custom-active-button active-value="3600" inactive-value="">1小时</custom-active-button>
          <custom-active-button active-value="31536000" inactive-value=""
            >不限时</custom-active-button
          >
          <custom-active-button active-value="自定义" inactive-value=""
            >自定义</custom-active-button
          >
        </custom-active-button-group>
      </el-form-item>
      <el-form-item
        label="自定义时长"
        v-if="showTime"
        required
        :rules="[
          {
            required: true,
            message: '请选择或输入工单时长',
            trigger: 'blur'
          }
        ]"
      >
        <el-input-number
          v-model="customizeTime"
          controls-position="right"
          placeholder="请输入以分钟为单位的时长"
          :min="1"
        />
        <span mt-10>分钟</span>
      </el-form-item>
      <el-form-item prop="imageUrl" label="相关照片">
        <el-upload
          :action="action"
          ref="upload"
          :headers="{ Authorization: getToken() ?? '' }"
          :on-success="OnSuccess"
          accept=".png,.jpg"
          name="file"
          list-type="picture-card"
          :limit="2"
          :on-exceed="handleExceed"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item prop="remark" label="工单详情">
        <el-input
          v-model="form.remark"
          type="textarea"
          :autosize="{ minRows: 5 }"
          placeholder="请输入工单详情"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="reset">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
:deep(.el-upload--picture-card) {
  --el-upload-picture-card-size: 100px;
}
:deep(.el-upload-list--picture-card) {
  --el-upload-list-picture-card-size: 100px;
}
.el-dialog .el-dialog__body > .el-form {
  width: 90%;
}
:deep(.el-cascader) {
  width: 100%;
}
</style>
